/*
 * Database.h
 *
 *  Created on: 09-Oct-2009
 *      Author: Atul Shukla (atul.shukla@iiitb.net)
 */

/*
 * A database is a fixed size file,
 * and pages (in the file) on disk are managed by the disk space manager (DSM).
 *
 * DSM is the component that takes care of
 * the allocation and deallocation of pages within a database.
 * It also performs reads and writes of pages to and from disk,
 * and provides a logical file layer within the context of a database management system.
 */

#ifndef DISKSPACEMANAGER_H_
#define DISKSPACEMANAGER_H_
#include<fstream>
#include<iostream>
#include"../common.h"
#include"../Page.h"
#define DB_EXT_SIZE 10
using namespace std;


struct DBHeader {
		char name[MAX_FILE_NAME];
		int value;
		char flag;
	};


class Database {
private:


	fstream file;

	char *spaceMap;// map of allocation of pages 0 for !allocated 1 for allocated
	int nextEmptyPage,freeList; //stores page number which can be allocated, initially 0
	int runSize;
	string databaseName;


public:
	void saveState();
	int getFreeList() ;
	int getNextEmptyPage() ;
	/**************Database Management********************/

	// Constructors
	// Create a database with the specified number of pages where the page
	// size is the default page size.
	Database(const char* name, unsigned numPages, Status& status);

	// Open the database with the given name.
	Database(const char* name, Status& status);

	// Destructor: closes the database
	~Database();

	// Destroy the database, removing the file that stores it.
	Status destroy(char* name);

	/**************Page Management********************/

	// Read the contents of the specified page into the given memory area.
	Status readPage(int pageNo, Page* pagePtr);

	// Write the contents of the specified page.
	Status writePage(int pageNo, Page* pagePtr);

	// Allocate a set of pages where the run size is taken to be 1 by default.
	// Gives back the page number of the first page of the allocated run.
	Status allocatePage(int& startPageNum);

	// Deallocate a set of pages starting at the specified page number and
	// a run size can be specified.
	Status deallocatePage(int startPageNum);


	/**********************General************************/

	// Functions to return some characteristics of the database.
	const string getName();
	int getNumPages();
	int getPageSize();
    void view(Page *p);


};

namespace DatabaseUI{
void dUI(Database * db);
}

#endif /* DISKSPACEMANAGER_H_ */
